﻿using System.ComponentModel.Composition;
using System.IO;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;

namespace WeavingCommon
{
    [Export, PartCreationPolicy(CreationPolicy.Shared)]
    public class ModuleReader 
    {
        IConfig config;
        IAssemblyResolver assemblyResolver;
        public ModuleDefinition Module { get; set; }

        [ImportingConstructor]
        public ModuleReader(IConfig config, IAssemblyResolver assemblyResolver)
        {
            this.config = config;
            this.assemblyResolver = assemblyResolver;
        }

        static ISymbolReaderProvider GetSymbolReaderProvider(string targetPath)
        {
            var pdbPath = Path.ChangeExtension(targetPath, "pdb");
            if (File.Exists(pdbPath))
            {
                return new PdbReaderProvider();
            }
            var mdbPath = Path.ChangeExtension(targetPath, "mdb");

            if (File.Exists(mdbPath))
            {
                return new MdbReaderProvider();
            }
            return null;
        }

        public void Execute()
        {
            var readerParameters = new ReaderParameters
            {
                AssemblyResolver = assemblyResolver,
                ReadSymbols = true,
                SymbolReaderProvider = GetSymbolReaderProvider(config.TargetPath),
            };
            Module = ModuleDefinition.ReadModule(config.TargetPath, readerParameters);
        }
    }
}